package com.twelve.all.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.darsh.multipleimageselect.activities.AlbumSelectActivity;
import com.darsh.multipleimageselect.helpers.Constants;
import com.darsh.multipleimageselect.models.Image;
import com.twelve.all.R;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.PictureUtil;
import com.twelve.all.utils.ToastUtil;
import com.twelve.all.utils.Tools;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by 张龙臣 on 2019/1/21.
 */

public abstract class CameraFragment extends PremissionFragment {
    public static final int RESULT_LOAD_IMAGE = 101;
    public static final int RESULT_CAMERA_IMAGE = 102;
    public static String mCurrentPhotoPath;
    private Handler mHandler;

    protected boolean mUpLoadNow = true;

    protected List<String> urls = new ArrayList<>();

    protected int mUpLoadCount = 0;

    @Override
    public void onDestroy() {
        super.onDestroy();
        urls.clear();
    }

    /**
     * 文件转base64字符串
     *
     * @param file
     * @return 在子线程中调用该方法
     */
    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            int length = in.read(bytes);
            base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
//            BASE64Encoder encoder = new BASE64Encoder();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return base64;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();
    }

    @Override
    protected void onGranted(int requestCode) {
        Log.e("onGranted", "-----------requestCode  =   " + requestCode);
        switch (requestCode) {
            case CAMERA_CODE:
                takeCamera(RESULT_CAMERA_IMAGE);
                break;
            case STORAGE_CODE:
//                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(i, RESULT_LOAD_IMAGE);
                Intent intent = new Intent(getContext(), AlbumSelectActivity.class);
                intent.putExtra(Constants.INTENT_EXTRA_LIMIT, 1);
                startActivityForResult(intent, RESULT_LOAD_IMAGE);
                break;
            case 1:
                cameraTask();//相机也要存储权限
                break;
        }
    }

    @Override
    protected void onProhibited(int requestCode) {
        Log.e("onProhibited", "-----------requestCode  =   " + requestCode);
        switch (requestCode) {
            case CAMERA_CODE:
                Toast.makeText(Tools.getAppContext(), "没有相机权限", Toast.LENGTH_SHORT).show();
                break;
            case STORAGE_CODE:
                Toast.makeText(Tools.getAppContext(), "没有文件访问权限", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    public void showCameraPop() {
        View popView = View.inflate(getActivity(), R.layout.popupwindow_camera_need, null);
        Button bt_album = popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = this.getResources().getDisplayMetrics().widthPixels;
        int height = this.getResources().getDisplayMetrics().heightPixels / 3;

        final PopupWindow popupWindow = new PopupWindow(popView, weight, height);
//        popupWindow.setAnimationStyle(R.style.anim_popup_dir);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                    strorageTask();
                else {
                    Toast.makeText(Tools.getAppContext(), "SD卡未插入", Toast.LENGTH_SHORT).show();
                }
                popupWindow.dismiss();

            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                    if (Build.VERSION.SDK_INT >= 23) {
                        int check = ContextCompat.checkSelfPermission(Tools.getAppContext(), permissions[0]);
                        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                        if (check == PackageManager.PERMISSION_GRANTED) {
                            cameraTask();
                        } else {
                            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        }
                    } else {
                        cameraTask();
                    }
                } else {
                    Toast.makeText(Tools.getAppContext(), "SD卡未插入", Toast.LENGTH_SHORT).show();
                }
                popupWindow.dismiss();
            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕变为不透明
        assert getActivity() != null;
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1.0f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.5f;
        getActivity().getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50);
    }

    public void takeCamera(int num) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        assert getActivity() != null;
        if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            photoFile = createImageFile();
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri uri = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(getActivity(), "com.hangwei.supplychain.dispatch.fileprovider", photoFile);
                } else uri = Uri.fromFile(photoFile);
                //添加权限
                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(takePictureIntent, num);//跳转界面传回拍照所得数据
            } else {
                Log.e("mCurrentPhotoPath", "mCurrentPhotoPath    为空-------------------------");
            }
        } else {
            Log.e("MediaStore", "MediaStore   没有找到相机-------------------------");
        }
    }

    private File createImageFile() {
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File image = null;
        try {
            image = File.createTempFile(
                    generateFileName(),  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private String generateFileName() {
        @SuppressLint("SimpleDateFormat")
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        return "JPEG_" + timeStamp + "_";
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
//            if (requestCode == RESULT_LOAD_IMAGE && null != data) {
//                Uri selectedImage = data.getData();
//                String[] filePathColumn = {MediaStore.Images.Media.DATA};
//                assert getActivity() != null;
//                Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
//                cursor.moveToFirst();
//                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                final String picturePath = cursor.getString(columnIndex);
//                Log.i("onActivityResult", "---AAAAAAAAA---picturePath---------" + picturePath);
//                if (PictureUtil.isPicture(picturePath)) {
//                    showPic(picturePath);
//                    if (mUpLoadNow)
//                        upLoadImg(picturePath);
//                    else urls.add(picturePath);
//                } else ToastUtil.showToast("请选择图片");
//                cursor.close();
            ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
            for (Image img : images) {
                LogUtil.i(img.id + "---" + img.name + "---" + img.isSelected + "---" + img.path);
                showPic(img.path);
                if (mUpLoadNow)
                    upLoadImg(img.path);
                else urls.add(img.path);
            }
        } else if (requestCode == RESULT_CAMERA_IMAGE) {
            Log.i("onActivityResult", "---AAAAAAAAA--mCurrentPhotoPath----------" + mCurrentPhotoPath);
            if (PictureUtil.isPicture(mCurrentPhotoPath)) {
                showPic(mCurrentPhotoPath);
                if (mUpLoadNow)
                    upLoadImg(mCurrentPhotoPath);
                else urls.add(mCurrentPhotoPath);
            } else ToastUtil.showToast("请选择图片");
        }
    }

    private void upLoadImg(final String picturePath) {
        Log.d("upLoadImg--picturePath", picturePath);
        new Thread(new Runnable() {
            @Override
            public void run() {
                final File file = compressImage2File(compressImageFromFile(picturePath, 1080));
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        upLoadCompressedImg(file, picturePath);
                    }
                });
            }
        }).start();
    }

    private void showPic(final String picturePath) {
        assert getActivity() != null;
        final Dialog dialog = new LoadingDialog(getActivity(), "图片处理中");
        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = compressImage2Bitmap(compressImageFromFile(picturePath, 1080));
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (dialog.isShowing()) dialog.dismiss();
                        showCompressedPic(bitmap, picturePath);
                    }
                });
            }
        }).start();
    }

    /**
     * @param file        压缩后的图片文件 不超过100K
     * @param picturePath 图片在手机的全路径
     */
    protected abstract void upLoadCompressedImg(File file, String picturePath);

    /**
     * @param bitmap      压缩后的bitmap 不超过100K
     * @param picturePath 图片在手机的全路径
     */
    protected abstract void showCompressedPic(Bitmap bitmap, String picturePath);

    protected void upLoadAllCompressedImg() {
        if (urls != null && urls.size() != 0) {
            for (String url : urls) {
                upLoadImg(url);
            }
        }
    }

    /**
     * 按尺寸压缩图片
     *
     * @param srcPath  图片路径
     * @param desWidth 压缩的图片宽度
     * @return Bitmap 对象
     */
    public Bitmap compressImageFromFile(String srcPath, float desWidth) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;//只读边,不读内容
        Bitmap bitmap;
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float desHeight = desWidth * h / w;
        int be = 1;
        if (w > h && w > desWidth) {
            be = (int) (newOpts.outWidth / desWidth);
        } else if (w < h && h > desHeight) {
            be = (int) (newOpts.outHeight / desHeight);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置采样率
//        newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;
    }

    /**
     * 压缩图片（质量压缩）
     *
     * @param image
     */
    public File compressImage2File(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            if (options == 10)
                break;
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        File file = new File(Environment.getExternalStorageDirectory() + "/temp.png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file;
    }

    public Bitmap compressImage2Bitmap(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            if (options == 10)
                break;
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);
    }

}
